import { DomLayerNode } from "./dom_layer_node";

const { executeInEditMode, ccclass, property } = cc._decorator;

@ccclass
export default class DomLayerImage extends DomLayerNode {
    @property({
        serializable: true
    })
    _asset: cc.Asset = null;
    @property(cc.Asset)
    get asset() {
        return this._asset;
    }
    set asset(asset: cc.Asset) {
        this._asset = asset;
        this.src = asset.nativeUrl;
    }
    @property({
        serializable: true,
        visible: false
    })
    _src = "";
    @property({
        visible: function () {
            return !this.asset;
        }
    })
    get src() {
        return this._src;
    }
    set src(val) {
        if (val != this._src) {
            this.imageLoaded = false;
        }
        this._src = val;
        if (this.ele) {
            this.ele["src"] = val;
        }
    }

    lateSrc = "";
    imageLoaded = false;
    imgWidth = 0;
    imgHeight = 0;

    @property({
        serializable: true
    })
    _touch = false;
    @property
    get touch() {
        return this._touch;
    }
    set touch(val) {
        this._touch = val;
        if (!this._touch) {
            Object.assign(this.ele.style, {
                pointerEvent: "none"
            });
        }
        else {
            Object.assign(this.ele.style, {
                pointerEvent: ""
            });
        }
    }

    @property
    autoResize = false;

    createElement(): void {
        let img = new Image();
        Object.assign(img.style, {
            position: "absolute",
        });
        if (!this.touch) {
            Object.assign(img.style, {
                pointerEvent: "none"
            });
        }
        img.src = this.src;
        img.onload = () => {
            this.imgWidth = img.naturalWidth;
            this.imgHeight = img.naturalHeight;
            this.imageLoaded = true;
            if (this.autoResize) {
                let wph = this.imgWidth / this.node.width;
                this.node.height = this.imgHeight / wph;
            }
        };

        this.ele = img;
        document.body.appendChild(this.ele);
    }
    destroyElement() {
        if (this.ele) {
            document.body.removeChild(this.ele);
            this.ele = null;
        }
    }
};